<!--
 * @Date: 2023-06-20 19:20:53
 * @LastEditTime: 2023-09-01 14:28:06

 * 介绍:
-->
<script lang="ts" setup>
import { RpopoverConfig } from "./index";
import {
  PopoverAction,
  PopoverTheme,
  PopoverTrigger,
  PopoverPlacement,
} from "vant";
import { StyleValue } from "vue";
import { filterObject } from "@@/utils/tools/object";

const props = withDefaults(
  defineProps<{
    actions?: PopoverAction[];
    theme?: PopoverTheme;
    trigger?: PopoverTrigger;
    duration?: StrNumber;
    overlay?: boolean;
    overlayClass?: any;
    overlayStyle?: StyleValue;
    showArrow?: boolean;
    closeOnClickAction?: boolean;
    closeOnClickOutside?: boolean;
    closeOnClickOverlay?: boolean;
    teleport?: string | Element;
    iconPrefix?: string;
    show?: boolean;
    offset?: [number, number];
    placement?: PopoverPlacement;
  }>(),
  {
    closeOnClickAction: true,
    closeOnClickOutside: true,
    closeOnClickOverlay: true,
    showArrow: true,
    show: undefined,
  }
);

const slot = useSlots();
const config = ref<RpopoverConfig>(initCfg());

const emit = defineEmits<{
  (e: "select", action: PopoverAction, index: number): void;
  (e: "open"): void;
  (e: "close"): void;
  (e: "opened"): void;
  (e: "closed"): void;
  (e: "click-overlay"): void;
  (e: "update:show", v: boolean): void;
}>();
function open(cfg?: Partial<RpopoverConfig>) {
  config.value = { ...initCfg(), ...cfg, show: true };
}
function close() {
  config.value.show = false;
}
defineExpose({ open, close });
function initCfg() {
  return {
    show: false,
    placement: undefined,
    offset: undefined,
  };
}
const $show = computed({
  get() {
    console.log(typeof props.show === "boolean");
    
    if (typeof props.show === "boolean") return props.show;
    return config.value.show;
  },
  set(v) {
    emit("update:show", Boolean(v));
  },
});
const $offset = computed(() =>
  props.offset ? props.offset : config.value.offset
);
const $placement = computed(() =>
  props.placement ? props.placement : config.value.placement
);
</script>
<template>
  <van-popover
    class="shadow"
    v-bind=" { ...filterObject(props) as any, ...filterObject(config) }"
    :placement="$placement"
    :offset="$offset"
    v-model:show="$show"
    @select="(e1, e2) => emit('select', e1, e2)"
    @open="emit('open')"
    @close="emit('close')"
    @opened="emit('opened')"
    @click-overlay="emit('click-overlay')"
  >
    <template v-if="slot.reference" #reference>
      <slot name="reference"></slot>
    </template>
    <template v-if="slot.default" #default>
      <slot name="default"></slot>
    </template>
    <template
      v-if="slot.action"
      #action="action: { action: PopoverAction, index: number }"
    >
      <slot name="action" v-bind="action">{{ action }}</slot>
    </template>
  </van-popover>
</template>
<style lang="scss" scoped></style>
